<?php

namespace App\Models\Api;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use App\Models\Admin\SalesStrategyViewPermissions;

class SalesStrategy extends Model
{

    protected $table = 'sales_strategy';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 优惠事件
     * @param $money
     * @param array $ids
     * @param int $num
     * @return array
     * Note: 
     * - goodsMoney 只计算非赠品商品金额(is_give=0)
     * - 赠品商品(is_give=1)不参与订单金额和运费计算
     */
    public static function getAllGoodsList($store_id, $ids = [], $num = 0)
    {
        $goodsArr = [];
        $goodsIds = [];
        $goodsList = [];
        $giveList = [];
        $totalNum = 0;
        $goodsNum = 0;
        $goodsMoney = 0;
        $goodsPriceTotal = 0;
        if ($num > 0) {
            $list = self::getDanGoodsList($ids, $store_id, $num);
        } else {
            $list = self::getGoodsList($ids, $store_id);
        }
        if ($list) {
            foreach ($list as $vv) {
                // 处理 goods_num 兼容数组和数字
                $num = 0;
                if (is_array($vv['goods_num'])) {
                    foreach ($vv['goods_num'] as $v) {
                        $num += intval($v);
                    }
                } else {
                    $num = intval($vv['goods_num']);
                }

                // 只有非赠品且goods_pid为0的商品才计算价格（普通商品或组合商品主商品）
                if ($vv['is_give'] == 0 && ($vv['goods_pid'] ?? 0) == 0) {
                    $goodsIds[] = $vv['goods_id'];
                    $goodsNum += $num;
                    $goodsMoney += $num * $vv['sale_price'];
                    $goodsPriceTotal += $num * $vv['goods_price'];
                }
            }
            # 金额赠送
            $arr1 = self::getManZenByMoney($goodsMoney, $store_id);
            # 单品赠送
            $arr2 = self::getManZenByGoodsId($store_id, $list);

            # 数量赠送
            $arr3 = self::getManZenByNum($goodsNum);
            $goodsArr = array_merge($list, $arr1, $arr2, $arr3);
            foreach ($goodsArr as $kk => $vv) {
                // 兼容 goods_num 为数组或数字
                $num = 0;
                if (is_array($vv['goods_num'])) {
                    foreach ($vv['goods_num'] as $v) {
                        $num += intval($v);
                    }
                } else {
                    $num = intval($vv['goods_num']);
                }
                $totalNum += $num;
                if ($vv['is_give'] == 0) {
                    // 赋值时也用 $num
                    $vv['goods_num'] = $num;
                    $goodsList[] = $vv;
                } elseif ($vv['is_give'] == 1) {
                    if (isset($giveList[$vv['goods_id']])) {
                        $giveList[$vv['goods_id']]['goods_num'] += $num;
                    } else {
                        $vv['goods_num'] = $num;
                        $giveList[$vv['goods_id']] = $vv;
                    }
                }
            }
            $info['goodsMoney'] = $goodsMoney;
            $info['goodsPrice'] = $goodsPriceTotal;
            $info['goodsNum'] = $goodsNum;
            $info['group_num'] = $goodsNum;
            $info['totalNum'] = $totalNum;
            $info['goods_list'] = $goodsList;
            $info['goods_give_list'] = array_values($giveList);
            return $info;
        }
        return [];
    }

    /**
     * 获取商品
     * @param $ids
     * @param $store_id
     */
    public static function getDanGoodsList($goods_id, $store_id, $num)
    {
        $list = [];
        $goodsInfo = GoodsStore::from('goods_store as gs')->leftJoin('goods as g', 'g.id', '=', 'gs.goods_id')
            ->where(['gs.store_id' => $store_id, 'gs.goods_id' => $goods_id])
            ->select(['gs.goods_id','g.goods_weight_m', 'gs.mini_quantity', 'g.goods_img', 'g.goods_name','g.goods_price', 'gs.sale_price', 'gs.buy_num', 'gs.get_num'])->first();
        if ($goodsInfo) {
            // 代发
//            $is_agent = Store::where(['id' => $store_id])->value('is_agent');
//            if ($goodsInfo['mini_quantity'] > $num && $is_agent != 1) {
            if ($goodsInfo['mini_quantity'] > $num) {
                errorMsg("{$goodsInfo['goods_name']}的最低起订量为{$goodsInfo['mini_quantity']}");
            }
            $list[] = [
                'goods_id' => $goodsInfo['goods_id'],
                'is_give' => 0,
                'type' => 1,
                'goods_name' => $goodsInfo['goods_name'],
                'sale_price' => $goodsInfo['sale_price'],
                'goods_img' => $goodsInfo['goods_img'],
                'goods_num' => $num,
                'goods_price' =>  $goodsInfo['goods_price'],
                'goods_weight_m' => $goodsInfo['goods_weight_m'],
                'mini_quantity' => $goodsInfo['mini_quantity']
            ];
            if (($num >= $goodsInfo['buy_num']) && $goodsInfo['get_num']) {
                $newNum = intval($num / $goodsInfo['buy_num']) * $goodsInfo['get_num'];
                $list[] = [
                    'goods_id' => $goodsInfo['goods_id'],
                    'is_give' => 1,
                    'type' => 1,
                    'goods_name' => $goodsInfo['goods_name'],
                    'sale_price' => $goodsInfo['sale_price'],
                    'goods_img' => $goodsInfo['goods_img'],
                    'goods_num' => $newNum,
                    'goods_weight_m' => $goodsInfo['goods_weight_m'],
                    'mini_quantity' => $goodsInfo['mini_quantity']
                ];
            }
        }
        return $list;
    }

    /**
     * 获取商品
     * @param $ids
     * @param $store_id
     */
    public static function getGoodsList($ids, $store_id)
    {
        if ($ids && $store_id) {
            $goodsArr = [];
            $list1 = StoreCart::from('store_cart as s')
                ->select(['s.id', 's.is_give', 's.goods_group', 's.type', 's.goods_id', 's.goods_pid','g.goods_price','g.goods_group', 's.goods_num', 'g.goods_name', 'gs.mini_quantity', 'g.goods_img', 'gs.sale_price', 'gs.buy_num', 'gs.get_num','g.goods_weight_m'])
                ->leftJoin('goods as g', 'g.id', '=', 's.goods_id')
                ->leftJoin('goods_store as gs', 'gs.goods_id', '=', 's.goods_id')
                ->where(['s.store_id' => $store_id, 'gs.store_id' => $store_id])->whereIn('s.id', $ids)->get()->toArray();

            if ($list1) {
                // 代发
//                $is_agent = Store::where(['id' => $store_id])->value('is_agent');
                # 合并数据
                foreach ($list1 as $kk => $item) {
//                 if ($item['mini_quantity'] > $item['goods_num'] && $is_agent != 1) {
                   if ($item['mini_quantity'] > $item['goods_num']) {
//                       var_dump(json_encode($item));die();
                       errorMsg("{$item['goods_name']}的最低起订量为{$item['mini_quantity']}");
                   }
                    // 添加单个商品和组合商品主商品
                    if ($item['type'] == 1 || ($item['type'] == 2 && ($item['goods_pid'] ?? 0) == 0)) {
                        $goodsArr[] = $item;
                    }
                }
                # 组合数据
                $list2 = StoreCart::from('store_cart as s')
                    ->select(['s.id', 's.is_give', 's.goods_group', 's.type', 's.goods_id', 's.goods_pid', 's.goods_num','g.goods_price', 'g.goods_name', 'g.goods_img', 'gs.sale_price', 'gs.buy_num', 'gs.get_num','g.goods_weight_m'])
                    ->leftJoin('goods as g', 'g.id', '=', 's.goods_id')
                    ->leftJoin('goods_store as gs', 'gs.goods_id', '=', 's.goods_id')
                    ->where(['s.store_id' => $store_id, 'gs.store_id' => $store_id, 's.type' => 2])->whereIn('s.goods_pid', $ids)->get()->toArray();

                if ($list2) {
                    foreach ($list2 as $kk => $item) {
                        $goodsArr[] = $item;
                    }
                }

                foreach ($goodsArr as $key => $item) {
                    if ($item['type'] == 1) {
                        if (($item['goods_num'] >= $item['buy_num']) && $item['get_num']) {
                            $item['is_give'] = 1;
                            $item['goods_num'] = intval($item['goods_num'] / $item['buy_num']) * $item['get_num'];
                            $goodsArr[] = $item;
                        }
                    }
                }
                return $goodsArr;
            }
        }
        return [];
    }

    /**
     * 获取满赠
     */
    public static function getManZenByMoney($money, $store_id)
    {
        if ($money > 0) {
            $nowTime = time();
            $info = self::where('start', '<', $nowTime)->where('end', '>', $nowTime)->where(['type' => 1])->first();
            if ($info) {
                // 判断销售策略权限
                $permission = SalesStrategyViewPermissions::where('store_id', $store_id)->first();
                if ($permission){
                    $goods_ids = explode(',', $permission["goods_ids"]);
                }
                if ($money > $info['amount'] && in_array($info['id'], $goods_ids)) {
                    $goodsArr = [];
                    $send_goods = json_decode($info['send_goods'], true);
                    if ($send_goods) {
                        foreach ($send_goods as $kk => $send_good) {
                            $goodsInfo = Goods::getInfoById($send_good['id']);
                            $tmp['goods_id'] = $send_good['id'];
                            $tmp['goods_num'] = $send_good['number'];
                            $tmp['goods_name'] = $goodsInfo['goods_name'];
                            $tmp['goods_img'] = $goodsInfo['goods_img'];
                            $tmp['goods_price'] = $goodsInfo['goods_price'];
                            $tmp['type'] = 3;
                            $tmp['is_give'] = 1;
                            $goodsArr[] = $tmp;
                        }
                        return $goodsArr;
                    }
                }
            }
        }
        return [];
    }

    /**
     * 单品满赠-旧方法
     * @param $ids
     */
    public static function getManZenByGoodsIdOld($goodsIds, $store_id)
    {
        if ($goodsIds) {
            $nowTime = time();
            $listArr = self::whereIn('goods_id', $goodsIds)->where('start', '<', $nowTime)->where('end', '>', $nowTime)->where(['type' => 2])->get()->toArray();

            if ($listArr) {
                $goodsArr = [];
                foreach ($listArr as $info) {
                    $send_goods = json_decode($info['send_goods'], true);
                    $goods_num = StoreCart::where(['store_id' => $store_id, 'goods_id' => $info['goods_id'], 'type' => 1])->value('goods_num');
                    if ($info['goods_number'] <= $goods_num && $send_goods) {
                        $goodsNum = intval($goods_num / $info['goods_number']);
                        foreach ($send_goods as $kk => $send_good) {
                            $goodsInfo = Goods::getInfoById($send_good['id']);
                            $tmp['goods_id'] = $send_good['id'];
                            $tmp['goods_num'] = $send_good['number'] * $goodsNum;
                            $tmp['goods_name'] = $goodsInfo['goods_name'];
                            $tmp['goods_img'] = $goodsInfo['goods_img'];
                            $tmp['goods_price'] = $goodsInfo['goods_price'];
                            $tmp['type'] = 3;
                            $tmp['is_give'] = 1;
                            $goodsArr[] = $tmp;
                        }
                    }
                }
                return $goodsArr;
            }
        }
        return [];
    }

    /**
     * 单品满赠
     * @param $ids
     */
    public static function getManZenByGoodsId($store_id, $list)
    {
        $goodsArr = [];
        if ($list) {
            $nowTime = time();
            foreach ($list as $item) {
                $goods_id = $item['goods_id'];
                $goods_num = $item['goods_num'];
                    // 查询 可用的单品满赠商品
                $listArr = self::where('goods_id', $goods_id)->where('start', '<', $nowTime)->where('end', '>', $nowTime)->where(['type' => 2])->get()->toArray();
                if ($listArr) {
                    foreach ($listArr as $info) {
                        $send_goods = json_decode($info['send_goods'], true);
                        // 判断代理商是否有销售策略权限
                        $permission = SalesStrategyViewPermissions::where('store_id', $store_id)->first();
                        // 初始化$goods_ids为空数组
                        $goods_ids = [];
                        if ($permission && !empty($permission["goods_ids"])){
                            $goods_ids = explode(',', $permission["goods_ids"]);
                        }

                        // 计算赠送倍数
                        if ($info['goods_number'] <= $goods_num && $send_goods && !empty($goods_ids) && in_array($info['id'], $goods_ids)) {
                            $multiple = intval($goods_num / $info['goods_number']); // 计算倍数
                            foreach ($send_goods as $kk => $send_good) {
                                $goodsInfo = Goods::getInfoById($send_good['id']);
                                $tmp['goods_id'] = $send_good['id'];
                                $tmp['goods_num'] = $send_good['number'] * $multiple; // 赠品数量乘以倍数
                                $tmp['goods_name'] = $goodsInfo['goods_name'];
                                $tmp['goods_img'] = $goodsInfo['goods_img'];
                                $tmp['goods_price'] = $goodsInfo['goods_price'];
                                $tmp['type'] = 3;
                                $tmp['is_give'] = 1;
                                $goodsArr[] = $tmp;
                            }
                        }
                    }
                }
            }
        }
        return $goodsArr;
    }
    /**
     * 赠送纸袋
     * @param $num
     * {"goods_number":"1","send_goods":"[{\"id\":\"99\",\"number\":\"1\"},{\"id\":\"96\",\"number\":\"1\"},{\"id\":\"67\",\"number\":\"1\"}]"}
     */
    public static function getManZenByNum($num)
    {
        $info = Redis::get('DEFAULT:STRATEGY');
        if ($info && $num > 0) {
            $info = json_decode($info, true);
            if ($info && $info['send_goods'] && $num >= $info['goods_number']) {
                $goodsRate = intval($num / $info['goods_number']);
                $send_goods = json_decode($info['send_goods'], true);
                if ($send_goods) {
                    $goodsArr = [];
                    foreach ($send_goods as $kk => $send_good) {
                        $goodsInfo = Goods::getInfoById($send_good['id']);
                        $tmp['goods_id'] = $send_good['id'];
                        $tmp['goods_num'] = $send_good['number'] * $goodsRate;
                        $tmp['goods_name'] = $goodsInfo['goods_name'];
                        $tmp['goods_img'] = $goodsInfo['goods_img'];
                        $tmp['goods_price'] = $goodsInfo['goods_price'];
                        $tmp['type'] = 3;
                        $tmp['is_give'] = 1;
                        $goodsArr[] = $tmp;
                    }
                    return $goodsArr;
                }
            }
        }
        return [];
    }
}
